package com.sunyard.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
//import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunyard.constant.StatusConstant;
import com.sunyard.constant.manage.CommonConst;
import com.sunyard.constant.manage.OperatorConst;
import com.sunyard.constant.manage.StatusConstants;
import com.sunyard.dal.bo.*;
import com.sunyard.dal.bo.operator.*;
import com.sunyard.dal.bo.sys.AuditPasswordBo;
import com.sunyard.dal.bo.sys.AuthorityUpdateBo;
import com.sunyard.dal.bo.task.TaskFindBO;
import com.sunyard.dal.dto.LoginBackDTO;
import com.sunyard.dal.dto.OperatorDTO;
import com.sunyard.dal.dto.OtherParamDTO;
import com.sunyard.dal.dto.znsTask.TaskZNSDTO;
import com.sunyard.dal.entity.*;
import com.sunyard.dal.entity.suzhou.OrgInfoEntity;
import com.sunyard.dal.entity.suzhou.StaffAllOrgInfoEhrEntity;
import com.sunyard.dal.entity.suzhou.WarnVo;
import com.sunyard.dal.mapper.*;
import com.sunyard.dal.mapper.suzhou.OrgInfoMapper;
import com.sunyard.dal.mapper.suzhou.StaffAllOrgInfoEhrMapper;
import com.sunyard.dal.vo.inspect.PcInspect;
import com.sunyard.enums.TerminalTypeEnum;
import com.sunyard.manage.client.AuthorizationClient;
import com.sunyard.manage.constant.TblLogConst;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.manage.service.OperatorService;
import com.sunyard.manage.service.OrganizationService;
import com.sunyard.manage.util.DateFormatUtil;
import com.sunyard.manage.util.MD5Tool;
import com.sunyard.redisUtil.RedisUtil;
import com.sunyard.redisUtil.RedisUtils;
import com.sunyard.utils.DtoUtils;
import com.sunyard.utils.PrimaryKeyUtil;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import com.sunyard.utils.manage.DateFormat;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.client.Call;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @Title:
 * @Description:
 * @return:
 * @Author: jiy.fang
 * @Date: 2019/7/16 19:45
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class OperatorServiceImpl implements OperatorService {

    @Autowired
    private OperatorMapper operatorMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private PopedomMapper popedomMapper;

    @Autowired
    private OperatorCopyMapper operatorCopyMapper;

    @Autowired
    private BulletinMapper bulletinMapper;

    @Autowired
    private BulletinRelMapper bulletinRelMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OtherParamMapper otherParamMapper;

    @Autowired
    private AuthorizationClient authrozationClient;

    @Autowired
    private OperatorLogService operatorLogService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private TerminalCopyMapper terminalCopyMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private ZNSTaskMapper znsTaskMapper;

    @Autowired
    private OrganizationService organizationService;

    /**
     * 超级管理员
     */
    @Value("${admin.name}")
    private String adminName;
    /**
     * 超级审核员
     */
    @Value("${auditor.name}")
    private String auditorName;

    @Value("${operator.role.id}")
    private String adminRole;

    /**
     * 初始密码
     */
    @Value("${init.pwd}")
    private String initPwd;

    /**
     * 密码错误时间间隔
     */
    @Value("${login.errorTime.rang}")
    private String loginErrorTimeRang;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private StaffAllOrgInfoEhrMapper staffAllOrgInfoEhrMapper;

    @Autowired
    private OrgInfoMapper orgInfoMapper;


    /**
     * @Description: 用户登录
     * @Author: jiy.fang
     * @Date: 2019/7/17 9:20
     */
    @Override
//    @SentinelResource(value = "login")
    public BaseResult<LoginBackDTO> logIn(HttpServletResponse response, HttpServletRequest request, OperatorLoginBO operatorLoginBO) throws Exception {
        Operator loginOperator = operatorMapper.getOperatorByOpName(operatorLoginBO);
        if (loginOperator == null) {
            return GetResult.getResultErr("用户名不存在");
        }
        if ("2".equals(loginOperator.getLoginType())) {
            return GetResult.getResultErr("该用户登录方式为指纹登录！");
        }
        Boolean bool = null;
        //首次登录修改密码
        /*if ("1".equals(loginOperator.getFirstLogin())) {
            return GetResult.getFirstLoginResult();
        }*/
        if ("1".equals(loginOperator.getFirstLogin())
                && "1".equals(loginOperator.getLoginType())) {
            if (StringUtils.isNotBlank(loginOperator.getUpdateTime())){
                bool = DateFormatUtil.dateCompute(loginOperator.getUpdateTime());
            } else {
                bool = DateFormatUtil.dateCompute(loginOperator.getCreateTime());
            }
            if (bool){
                return GetResult.getResultErr("请找管理员重置密码！");
            }
        }
        // 用户状态0：启用 1：停用 2：注销 3：密码锁定
        if (StatusConstants.OPERATPR_LOCK.equals(loginOperator.getOpStatus().toString())) {
            return GetResult.getResultErr(OperatorConst.LOGIN_OP_LOCK_ERROR);
        }
        if (StatusConstants.OPERATPR_LOGOFF.equals(loginOperator.getOpStatus().toString())) {
            return GetResult.getResultErr("账户已经注销，无法登录");
        }
        if (StatusConstants.OPERATPR_DISABLE.equals(loginOperator.getOpStatus().toString())) {
            return GetResult.getResultErr("账户处于停用状态，无法登录");
        }
        //验证用户密码
        if (!loginOperator.getOpPwd().equals(operatorLoginBO.getOpPwd())) {
            if (adminRole.equals(loginOperator.getRoleId())) {
                log.info("密码错误，请输入正确的用户密码");
                return GetResult.getResultErr("账号密码错误");
            } else {
                // 进行密码输入错误次数的统计
                // 设定在30分钟内连续输入5次锁定账户
                Integer loginErrorTimeRangInt = Integer.parseInt(loginErrorTimeRang);
                if (loginErrorTimeRangInt > 0) {
                    long timeout = loginErrorTimeRangInt * 60;
                    Date beginTime = null;
                    if (loginOperator.getOpErrortime() != null && !"".equals(loginOperator.getOpErrortime())) {
                        beginTime = DateFormat.getDate("yyyy-MM-dd HH:mm:ss", loginOperator.getOpErrortime());
                    }
                    Date endTime = new Date();
                    if (beginTime != null && DateFormat.comPareDate(beginTime, endTime) < timeout) {
                        //密码错误次数加1
                        loginOperator.setOpPwdErrnum(loginOperator.getOpPwdErrnum() + 1);
                        loginOperator.setOpErrortime(DateFormat.dateTimeFormat1(endTime));
                    } else {
                        loginOperator.setOpPwdErrnum(1);
                        loginOperator.setOpErrortime(DateFormat.dateTimeFormat1(endTime));
                    }
                    //比较密码错误次数
                    OtherParam otherParam = otherParamMapper.queryByConfKey(OtherParam.LOGIN_FAIL_TIMES);
                    int loginErrorCount = Integer.parseInt(otherParam.getConfValue());
                    loginOperator.setUpdateTime(DateFormat.dateTimeFormat1(endTime));
                    //设置为空不更新该字段
                    loginOperator.setOpLastLoginTime(null);
                    if (loginErrorCount > 0 && loginOperator.getOpPwdErrnum() >= loginErrorCount) {
                        loginOperator.setOpStatus(Integer.parseInt(StatusConstants.OP_STATUS_LOCKED));
                        //更新用户表信息
                        operatorMapper.updateOperator(loginOperator);
                        return GetResult.getResultErr("账户被锁定，请联系管理员解锁");
                    } else {
                        //更新用户表信息
                        operatorMapper.updateOperator(loginOperator);
                        return GetResult.getResultErr("密码输入错误，您还剩" + (loginErrorCount - loginOperator.getOpPwdErrnum()) + "次机会输入正确的密码");
                    }
                }
            }
        }
        loginOperator.setOpPwdErrnum(0);
        loginOperator.setOpErrortime(null);
        loginOperator.setOpLastLoginTime(DateFormat.dateTimeFormat1(new Date()));
        //更新用户表信息
        operatorMapper.updateOperator(loginOperator);
        //继续判断登录条件
        return checkIsNeedChangePwd(response, request, loginOperator, operatorLoginBO.getOpPwd());
    }


    @Override
    public BaseResult<LoginBackDTO> logInById(HttpServletResponse response, HttpServletRequest request, String ticket) {
        String xml = getXml(ticket);
        String userId = readUserId(xml);
        if (StringUtils.isBlank(userId)) {
            return GetResult.getResultFail("没有找到ticket中的用户id");
        }
        Operator loginOperator = operatorMapper.getOperatorByOpId(userId);
        if (loginOperator == null) {
            return GetResult.getResultErr("用户Id不存在");
        }
        loginOperator.setOpPwdErrnum(0);
        loginOperator.setOpErrortime(null);
        loginOperator.setOpLastLoginTime(DateFormat.dateTimeFormat1(new Date()));
        //更新用户表信息
        operatorMapper.updateOperator(loginOperator);
        //继续判断登录条件
        log.info("登录类型:门户登录");
        //定义日志信息
        //检查用户是否有登录权限
        String key = "popedom:loginOperator:" + loginOperator.getRoleId();
        //获取权限
        List<Popedom> popedomList = popedomMapper.getPopedomByRoleId(loginOperator.getRoleId());
        RedisUtil.set(key, popedomList);
        if (popedomList.isEmpty()) {
            redisUtils.delete(key);
            return GetResult.getResultFail("没有任何管理权限,无法登陆");
        }
        LoginBackDTO loginBackDTO = operatorMapper.getBackInfoByOpId(loginOperator.getOpId());
        Map<String, String> map = new HashMap<>();
        map.put("username", loginOperator.getOpName());
        map.put("orgId", loginOperator.getOrgId());
        map.put("password", loginOperator.getOpPwd());
        map.put("applicationId", "ManageRealm");
        try {
            Map<String, String> authInfo = (Map<String, String>) authrozationClient.fetchToken(map);
            if (!"00".equals(authInfo.get("respCode"))) {
                return GetResult.getResultFail("获取权限失败");
            }
            response.setHeader("Authorization", authInfo.get("transInfo"));
            response.setHeader("Access-Control-Expose-Headers", "Authorization");
        } catch (Exception e) {
            e.printStackTrace();
            return GetResult.getResultFail("获取权限失败");
        }
        operatorLogService.insert("门户登录", "门户登录", "1", loginOperator.getOpId(), loginOperator.getOpName(), loginOperator.getOrgId());
        log.info("登录成功,用户ID={}，用户名={}", loginOperator.getOpId(), loginOperator.getOpName());
        return GetResult.getResult(loginBackDTO);
    }

    /**
     * @Description: 用户登出
     * @Author: jiy.fang
     * @Date: 2019/7/17 14:37
     */
    @Override
    public BaseResult logOut(HttpServletRequest request) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String roleId = TokenUtil.getRoleId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        redisUtils.delete(opId);
        redisUtils.delete("login:operator:" + opName);
        redisUtils.delete("popedom:loginOperator:" + opId);
//        redisUtils.delete("popedom:loginOperator:" + roleId);
//        redisUtils.delete("orgtreeid:" + orgId);
//        redisUtils.delete("orgid:" + orgId);
//        redisUtils.delete("allorgtree");
//        redisUtils.delete("popedom:all");
//        redisUtils.delete("popedomList:" + roleId);
        log.info("用户登出");
        //定义日志信息
        String logName = TblLogConst.OPERATOR_LOGINOUT;
        String operationDesc = "用户" + opName + "登出系统";
        operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
        return GetResult.getResultSuccess("退出登录成功");
    }

    /**
     * @Description: 修改用户密码
     * @Author: jiy.fang
     * @Date: 2019/7/17 14:36
     */
    @Override
    public BaseResult updatePwd(HttpServletRequest request, OperatorUpdatePwdBO operatorUpdatePwdBO) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        //定义日志信息
        String logName = "修改密码";
        String operationDesc = "用户" + opName + "进行修改密码";
        if (opId != null) {
            Operator operator = operatorMapper.getOperatorByOpId(opId);
            if (!operatorUpdatePwdBO.getOldPwd().equals(operator.getOpPwd())) {
                return GetResult.getResultFail("原密码输入错误");
            }
            if (operatorUpdatePwdBO.getNewPwd().equals(operator.getOpPwd())) {
                return GetResult.getResultFail("新密码不能与原密码相同");
            }
            if (operatorUpdatePwdBO.getNewPwd().equals(DigestUtils.md5DigestAsHex(initPwd.getBytes()))) {
                return GetResult.getResultFail("新密码不能与初始密码相同");
            }
            if (!operatorUpdatePwdBO.getNewPwd().equals(operatorUpdatePwdBO.getConfirmPwd())) {
                return GetResult.getResultFail("两次密码输入不一致");
            }
            if (operatorUpdatePwdBO.getNewPwd().equals(MD5Tool.MD5Encrypt(operator.getOpName()))) {
                return GetResult.getResultFail("新密码不能与用户名一致");
            }
            //修改用户密码
            operator.setOpPwd(operatorUpdatePwdBO.getNewPwd());
            operator.setFirstLogin("2");
            operatorMapper.updateOperator(operator);
            log.info("密码修改成功,用户ID={},用户名={}", operator.getOpId(), operator.getOpName());
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("密码修改成功");
        }
        return GetResult.getResultFail("请先登录系统");
    }

    /**
     * @Description: 分页查询用户信息
     * @Author: jiy.fang
     * @Date: 2019/7/23 9:56
     */
    @Override
    public BaseResult<DataGrid<Operator>> queryOrganizationByPage(HttpServletRequest request, PaginationBO<OperatorQueryBO> queryBO) throws Exception {
        OperatorQueryBO operatorQueryBO = queryBO.getParams();
        log.info("用户信息查询入参：{}", JSON.toJSONString(operatorQueryBO));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (StringUtils.isNotBlank(operatorQueryBO.getOrgId())) {
            orgId = operatorQueryBO.getOrgId();
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("opName", operatorQueryBO.getOpName());
        queryMap.put("opRealname", operatorQueryBO.getOpRealname());
        queryMap.put("roleId", operatorQueryBO.getRoleId());
        queryMap.put("opStatus", operatorQueryBO.getOpStatus());
        queryMap.put("adminName", adminName);
        queryMap.put("adminRole", adminRole);
        queryMap.put("auditorName", auditorName);
        List<String> orgIds = new ArrayList<>();
        //获取当前机构及下属机构id集合
        if (operatorQueryBO.getOrgId() == null || "".equals(operatorQueryBO.getOrgId())) {
            orgIds = getListOrgIds(orgId);
            orgIds.add(orgId);
            queryMap.put("list", orgIds);
        } else {
            orgIds.add(operatorQueryBO.getOrgId());
            queryMap.put("list", orgIds);
        }

        //设置分页信息
        PageHelper.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        //执行查询
        List<Operator> list = operatorMapper.getListOperatorByPage(queryMap);
        //取分页信息
        PageInfo<Operator> pageInfo = new PageInfo<>(list);
        //设置返回结果
        DataGrid<Operator> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal((int) total);
        dataGrid.setRows(list);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<DataGrid<WarnVo>> queryOperatorWarn(HttpServletRequest request, PaginationBO<OperatorQueryBO> queryBO) {
        //查询
        ArrayList<String> names = new ArrayList<>();
        names.add("admin");
        names.add("auditor");
        List<Operator> operatorsNotName = operatorMapper.getOperatorsNotName(names);
        List<StaffAllOrgInfoEhrEntity> staffAllOrgInfoEhrEntities = staffAllOrgInfoEhrMapper.selectAll();
        List<OrgInfoEntity> orgInfoEntities = orgInfoMapper.selectAll();
        Map<String, String> stringMap = orgInfoEntities.stream().filter(s -> StringUtils.isNotBlank(s.getBancsId())).collect(Collectors.toMap(OrgInfoEntity::getUnitId, OrgInfoEntity::getBancsId,(v1,v2) -> v1));
        for (StaffAllOrgInfoEhrEntity staffAllOrgInfoEhrEntity : staffAllOrgInfoEhrEntities) {
            staffAllOrgInfoEhrEntity.setBancsId(stringMap.get(staffAllOrgInfoEhrEntity.getOrgCode()));
        }
        ArrayList<WarnVo> warnVos = new ArrayList<>();
        Map<String, StaffAllOrgInfoEhrEntity> ehrEntityMap = staffAllOrgInfoEhrEntities.stream().filter(s -> StringUtils.isNotBlank(s.getEhrCode())).collect(Collectors.toMap(StaffAllOrgInfoEhrEntity::getEhrCode, t -> t,(v1,v2) -> v1));
        String warn = "";
        for (Operator operator : operatorsNotName) {
            warn = "";
            WarnVo warnVo = new WarnVo();
            warnVo.setOpName(operator.getOpName());
            warnVo.setOpRealname(operator.getOpRealname());
            warnVo.setOrgId(operator.getOrgId());
            StaffAllOrgInfoEhrEntity ehrEntity = ehrEntityMap.get(operator.getOpName());
            if (null != ehrEntity){
                warnVo.setImportBancsId(ehrEntity.getBancsId());
                warnVo.setImportEhrCode(ehrEntity.getEhrCode());
                warnVo.setImportStaffName(ehrEntity.getStaffName());
                if (StringUtils.isBlank(operator.getOrgId()) || StringUtils.isBlank(ehrEntity.getBancsId()) || !ehrEntity.getBancsId().equals(operator.getOrgId())){
                    warn = "机构号不匹配。";
                }else if (StringUtils.isBlank(operator.getOpRealname()) || StringUtils.isBlank(ehrEntity.getStaffName()) || !ehrEntity.getStaffName().equals(operator.getOpRealname())){
                    warn = "用户名不匹配。";
                }
            } else {
                warn = "用户信息不匹配。";
            }
            if (StringUtils.isBlank(warn)){
                continue;
            }
            warnVo.setWarn(warn);
            warnVos.add(warnVo);
        }
        PageInfo<WarnVo> pageInfo = new PageInfo<>(warnVos);
        DataGrid<WarnVo> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal((int) total);
        dataGrid.setRows(warnVos);
        return GetResult.getResult(dataGrid);
    }


    @Override
    public int queryOperatorWarnCount() {
        //查询
        ArrayList<String> names = new ArrayList<>();
        names.add("admin");
        names.add("auditor");
        List<Operator> operatorsNotName = operatorMapper.getOperatorsNotName(names);
        List<StaffAllOrgInfoEhrEntity> staffAllOrgInfoEhrEntities = staffAllOrgInfoEhrMapper.selectAll();
        List<OrgInfoEntity> orgInfoEntities = orgInfoMapper.selectAll();
        Map<String, String> stringMap = orgInfoEntities.stream().filter(s -> StringUtils.isNotBlank(s.getBancsId())).collect(Collectors.toMap(OrgInfoEntity::getUnitId, OrgInfoEntity::getBancsId,(v1,v2) -> v1));
        for (StaffAllOrgInfoEhrEntity staffAllOrgInfoEhrEntity : staffAllOrgInfoEhrEntities) {
            if (StringUtils.isNotBlank(staffAllOrgInfoEhrEntity.getOrgCode())){
                staffAllOrgInfoEhrEntity.setBancsId(stringMap.get(staffAllOrgInfoEhrEntity.getOrgCode()));
            }
        }
        Map<String, StaffAllOrgInfoEhrEntity> ehrEntityMap = staffAllOrgInfoEhrEntities.stream().filter(s -> StringUtils.isNotBlank(s.getEhrCode())).collect(Collectors.toMap(StaffAllOrgInfoEhrEntity::getEhrCode, t -> t,(v1,v2) -> v1));
        String warn = "";
        Integer count = 0;
        for (Operator operator : operatorsNotName) {
            warn = "";
            StaffAllOrgInfoEhrEntity ehrEntity = ehrEntityMap.get(operator.getOpName());
            if (null != ehrEntity){
                if (StringUtils.isBlank(operator.getOrgId()) || StringUtils.isBlank(ehrEntity.getBancsId()) || !ehrEntity.getBancsId().equals(operator.getOrgId())){
                    warn = "机构号不匹配。";
                }else if (StringUtils.isBlank(operator.getOpRealname()) || StringUtils.isBlank(ehrEntity.getStaffName()) || !ehrEntity.getStaffName().equals(operator.getOpRealname())){
                    warn = "用户名不匹配。";
                }
            } else {
                warn = "用户信息不匹配。";
            }
            if (StringUtils.isBlank(warn)){
                continue;
            }
            count++;
        }
        return count;
    }

    /**
     * @Description: 添加用户
     * @Author: jiy.fang
     * @Date: 2019/7/23 17:58
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult insertOperator(HttpServletRequest request, OperatorAddBO operatorAddBO) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        List<String> list = new ArrayList<>();
        list.add(OtherParam.OPERATOR_ADD_AUTH);
        List<OtherParamDTO> otherParams = otherParamMapper.queryByKeys(list);
        if (!CollectionUtils.isEmpty(otherParams)){
            OtherParam otherParam = otherParams.get(0);
            if ("0".equals(otherParam.getConfValue()) ) {
                operatorAddBO.setAuditType("1");
                operatorAddBO.setAuditor(opId);
            }
        }
        //定义日志信息
        String logName = TblLogConst.OPERATOR_ADD;
        String operationDesc = "操作人" + opName + " 添加了用户：" + operatorAddBO.getOpName();

        //判断用户名是否已经存在
        int existOpName = operatorMapper.existOpName(operatorAddBO.getOpName());
        if (existOpName > 0) {
            return GetResult.getResultFail("用户名已存在");
        }
        //判断用户名是否在临时表中已经存在
        int existOpNameCopy = operatorCopyMapper.existOpName(operatorAddBO.getOpName());
        if (existOpNameCopy > 0) {
            return GetResult.getResultFail("用户已在审核");
        }
        //添加用户到用户临时表
        OperatorCopy operatorCopy = new OperatorCopy();
        DtoUtils.cloneBeanToBean(operatorCopy, operatorAddBO);
        //生成审核ID
        operatorCopy.setAuditId(PrimaryKeyUtil.getPrimaryKey());
        operatorCopy.setAuditType(StatusConstant.AUDIT_TYPE_ADD);
        operatorCopy.setOpId(PrimaryKeyUtil.getPrimaryKey());
        operatorCopy.setOpPwd(DigestUtils.md5DigestAsHex(initPwd.getBytes()));
        operatorCopy.setCreateOp(opId);
        operatorCopy.setOpPwdErrnum(0);
        operatorCopy.setAuditSn(1);
        operatorCopy.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
        operatorCopy.setAuditOp(operatorAddBO.getAuditor());

        //同步审核时
        if ("1".equals(operatorAddBO.getAuditType())) {
            operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_PASS);
            Operator operator = new Operator();
            DtoUtils.cloneBeanToBean(operator, operatorCopy);
            //审核表直接通过
            operatorCopyMapper.insert(operatorCopy);
            //判断是否注销重开
            Operator operator2 = operatorMapper.getOperatorByOpNameString(operator.getOpName());
            int result;
            if (Objects.nonNull(operator2)) {
                operator.setOpId(null);
                result = operatorMapper.updateOperatorByOpName(operator);
            } else {
                result = operatorMapper.insertOperator(operator);
            }
            List<String> bulletinIdList = bulletinMapper.getBulletinIdList(operatorAddBO.getOrgId());
            for (String bulletinId : bulletinIdList) {
                BulletinRel bulletinRel = new BulletinRel();
                bulletinRel.setHasRead("0");
                bulletinRel.setIsDelete("0");
                bulletinRel.setBulletinId(bulletinId);
                bulletinRel.setOpId(operator.getOpId());
                bulletinRel.setOrgId(operator.getOrgId());
                bulletinRelMapper.insert(bulletinRel);
            }
            if (result > 0) {
                //详细日志添加
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("添加成功！");
            }
            return GetResult.getResultErr("添加失败！");
        }
        operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
        //返回处理结果
        int result = operatorCopyMapper.insert(operatorCopy);
        if (result > 0) {
            //详细日志添加
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("添加用户信息：添加成功，待审核。审核编号：{}", operatorCopy.getAuditId());
            return GetResult.getResultSuccess("添加成功，待审核！");
        }
        log.info("添加用户信息：添加失败");
        return GetResult.getResultFail("添加失败");

    }

    /**
     * @Description: 修改用户信息
     * @Author: jiy.fang
     * @Date: 2019/7/23 23:46
     */
    @Override
    public BaseResult updateOperator(HttpServletRequest request, OperatorUpdateBO operatorUpdateBO) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        //定义日志信息
        String logName = TblLogConst.OPERATOR_UPDATE;
        String operationDesc = "操作人" + opName + " 修改了用户：" + operatorUpdateBO.getOpName();

        Operator operator1 = operatorMapper.getOperatorByOpId(operatorUpdateBO.getOpId());
        //用户不能修改自己
        if (opId.equals(operator1.getOpId())) {
            return GetResult.getResultFail("不能修改当前登录用户");
        }
        //判断用户是否已经注销
        if (Integer.parseInt(StatusConstants.OPERATPR_LOGOFF) == operator1.getOpStatus()) {
            return GetResult.getResultFail("修改失败，该用户已经注销");
        }
        //判断用户是否是停用状态
        if (Integer.parseInt(StatusConstants.OPERATPR_DISABLE) == operator1.getOpStatus()) {
            return GetResult.getResultFail("修改失败，非停用状态无法修改");
        }
        //判断用户是否存在审核记录
        OperatorCopy operatorCopy1 = operatorCopyMapper.getOperatorCopyById(operatorUpdateBO.getOpId());
        if (operatorCopy1 != null) {
            return GetResult.getResultFail("修改失败,存在该用户的未审核信息");
        }
       /* if (!operator1.getOrgId().equals(operatorUpdateBO.getOrgId()) || !operator1.getRoleId().equals(operatorUpdateBO.getRoleId())) {
            //删除任务 目前直接修改状态，是否需要异步审核的时候再去删除
            znsTaskMapper.deleteBYOp(operator1.getOpName());
            terminalMapper.updateByAdminId(operator1.getOpId());
            int terminalCount = terminalMapper.getCountByAdminId(operatorUpdateBO.getOpId());
            if (terminalCount > 0) {
                return GetResult.getResultFail("用户" + operator1.getOpName() + "已绑定终端，无法修改角色和机构");
            }
            List<String> openLockOpList = taskMapper.getOpenLockOp();
            for (String openLockOp : openLockOpList) {
                String[] openLockOps = openLockOp.split(",");
                for (String name : openLockOps) {
                    if (name.equals(operator1.getOpName())) {
                        return GetResult.getResultFail("用户" + operator1.getOpName() + "已绑定任务，无法修改角色和机构");
                    }
                }
            }
        }*/
        //获取审核前的记录 用于审核前后对比
        OperatorDTO operatorDTO = operatorMapper.getOperatorDTOByOpId(operatorUpdateBO.getOpId());
        //将修改用户信息加到临时表
        OperatorCopy operatorCopy = new OperatorCopy();
        DtoUtils.cloneBeanToBean(operatorCopy, operator1);
        operatorCopy.setRoleId(operatorUpdateBO.getRoleId());
        operatorCopy.setOpRealname(operatorUpdateBO.getOpRealname());
        operatorCopy.setOpTel(operatorUpdateBO.getOpTel());
        operatorCopy.setOrgId(operatorUpdateBO.getOrgId());
        operatorCopy.setAuditId(PrimaryKeyUtil.getPrimaryKey());
        operatorCopy.setAuditType(StatusConstant.AUDIT_TYPE_UPDATE);
        operatorCopy.setCreateOp(opId);
        operatorCopy.setAuditSn(operatorCopyMapper.maxAuditSn(operator1.getOpId()) + 1);
        operatorCopy.setLoginType(operatorUpdateBO.getLoginType());
        operatorCopy.setAuditor(operatorUpdateBO.getAuditor());
        operatorCopy.setEntityRecord(JSON.toJSONString(operatorDTO));
        operatorCopy.setAuditOp(operatorUpdateBO.getAuditor());
        //同步审核时 直接通过 1 同步 2 异步
        if ("1".equals(operatorUpdateBO.getAuditType())) {
            operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_PASS);
            Operator operator = new Operator();
            DtoUtils.cloneBeanToBean(operator, operatorCopy);
            if (!operator1.getOrgId().equals(operatorUpdateBO.getOrgId()) || !operator1.getRoleId().equals(operatorUpdateBO.getRoleId())) {
                //删除任务 目前直接修改状态，是否需要异步审核的时候再去删除
                //删除调拨任务前清除锁具在新机构的有效任务
                resetBrcTask(operator1.getOpName());
                znsTaskMapper.deleteBYOp(operator1.getOpName());
                terminalMapper.updateByAdminId(operator1.getOpId());
            }
            //添加到审核表 状态为已审核
            operatorCopyMapper.insert(operatorCopy);
            //修改主表
            Integer result = operatorMapper.updateOperator(operator);
            if (result > 0) {
                //详细日志添加
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("修改成功！");
            }
            return GetResult.getResultErr("修改失败！");
        }
        operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
        int result1 = getResult1(operator1);
        //插入用户审核表
        int result2 = operatorCopyMapper.insert(operatorCopy);
        //返回处理结果
        if (result1 > 0 && result2 > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("修改成功，待审核！");
        }
        return GetResult.getResultFail("修改失败");
    }

    private int getResult1(Operator operator1) {
        //修改用户信息的审核状态 变为已审核
        operator1.setAuditStatus("1");
        return operatorMapper.updateOperatorAuditStatus(operator1);
    }

    /**
     * @Description: 删除用户
     * @Author: jiy.fang
     * @Date: 2019/7/23 23:46
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult deleteOperator(HttpServletRequest request, OperatorDeleteBO operatorDeleteBO) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Operator operator1 = operatorMapper.getOperatorByOpId(operatorDeleteBO.getOpId());
        //定义日志信息
        String logName = TblLogConst.OPERATOR_DELETE;
        String operationDesc = "操作人" + opName + " 删除了用户：" + operatorDeleteBO.getOpName();

        //判断被删除用户处于非"注销"状态且不在审核中  用户不能删除本用户
        if (opId.equals(operatorDeleteBO.getOpId())) {
            return GetResult.getResultFail("删除失败，您不能删除自身用户");
        }
        if (Integer.parseInt(StatusConstants.OPERATPR_LOGOFF) == operator1.getOpStatus()) {
            return GetResult.getResultFail("删除失败，该用户已经注销");
        }

        OperatorCopy operatorCopy = operatorCopyMapper.getOperatorCopyById(operatorDeleteBO.getOpId());
        if (operatorCopy != null) {
            return GetResult.getResultFail("删除失败,存在该用户的未审核信息");
        }
        operatorCopy = new OperatorCopy();
        DtoUtils.cloneBeanToBean(operatorCopy, operator1);
        //将删除信息添加到临时表
        operatorCopy.setAuditId(PrimaryKeyUtil.getPrimaryKey());
        operatorCopy.setAuditType(StatusConstant.AUDIT_TYPE_DELETE);
        operatorCopy.setCreateOp(opId);
        operatorCopy.setAuditSn(operatorCopyMapper.maxAuditSn(operator1.getOpId()) + 1);
        operatorCopy.setAuditor(operatorDeleteBO.getAuditor());
        operatorCopy.setAuditOp(operatorDeleteBO.getAuditor());
        //同步审核时 直接通过
        if ("1".equals(operatorDeleteBO.getAuditType())) {
            operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_PASS);
            Operator operator = new Operator();
            DtoUtils.cloneBeanToBean(operator, operatorCopy);
            operatorCopyMapper.insert(operatorCopy);
            int result = operatorMapper.deleteOperator(operator);
            if (result > 0) {
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("删除成功！");
            }
            return GetResult.getResultErr("删除失败！");
        }
        operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
        int result1 = getResult1(operator1);
        int result2 = operatorCopyMapper.insert(operatorCopy);
        //返回处理结果
        if (result1 > 0 && result2 > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("删除用户信息：删除成功，待审核。审核编号: {}", operatorCopy.getAuditId());
            return GetResult.getResultSuccess("删除成功，待审核！");
        }
        log.info("删除用户信息：删除失败");
        return GetResult.getResultFail("删除失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult batchDeleteOperator(HttpServletRequest request, OperatorDeleteBO deleteBO) throws Exception {
        String[] opids = deleteBO.getOpId().split(",");
        for (String operateId : opids) {
            OperatorDeleteBO operatorDeleteBO = new OperatorDeleteBO();
            BeanUtil.copyProperties(deleteBO, operatorDeleteBO);
            operatorDeleteBO.setOpId(operateId);
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            String opName = TokenUtil.getOpName(request.getHeader("token"));
            String orgId = TokenUtil.getOrgId(request.getHeader("token"));
            //定义日志信息
            String logName = "删除用户";
            String operationDesc = "操作人" + opName + " 删除了用户 ：" + operatorDeleteBO.getOpName();

            //判断被删除用户处于非"注销"状态且不在审核中  用户不能删除本用户
            if (opId.equals(operatorDeleteBO.getOpId())) {
                return GetResult.getResultFail("删除失败，您不能删除自身用户");
            }
            Operator operator1 = operatorMapper.getOperatorByOpId(operatorDeleteBO.getOpId());
            if (Integer.parseInt(StatusConstants.OPERATPR_LOGOFF) == operator1.getOpStatus()) {
                return GetResult.getResultFail("删除失败，该用户已经注销");
            }
            if (Integer.parseInt(StatusConstants.OPERATPR_DISABLE) != operator1.getOpStatus()) {
                return GetResult.getResultFail("删除失败，非停用状态无法删除");
            }
            OperatorCopy operatorCopy = operatorCopyMapper.getOperatorCopyById(operatorDeleteBO.getOpId());
            if (operatorCopy != null) {
                return GetResult.getResultFail("删除失败,存在该用户的待审核信息");
            }
            int terminalCount = terminalMapper.getCountByAdminId(operatorDeleteBO.getOpId());
            if (terminalCount > 0) {
                return GetResult.getResultFail("用户" + operator1.getOpName() + "已绑定终端，无法删除");
            }
            List<String> openLockOpList = taskMapper.getOpenLockOp();
            int flag = 0;
            for (String openLockOp : openLockOpList) {
                String[] openLockOps = openLockOp.split(",");
                for (String name : openLockOps) {
                    if (name.equals(operator1.getOpName())) {
                        flag++;
                    }
                }
            }
            if (flag > 0) {
                return GetResult.getResultFail("用户" + operator1.getOpName() + "已绑定任务，无法删除");
            }
            operatorCopy = new OperatorCopy();
            DtoUtils.cloneBeanToBean(operatorCopy, operator1);
            //将删除信息添加到临时表
            operatorCopy.setAuditId(PrimaryKeyUtil.getPrimaryKey());
            operatorCopy.setAuditType(StatusConstant.AUDIT_TYPE_DELETE);
            operatorCopy.setCreateOp(opId);
            operatorCopy.setAuditSn(operatorCopyMapper.maxAuditSn(operator1.getOpId()) + 1);
            operatorCopy.setAuditor(operatorDeleteBO.getAuditor());
            operatorCopy.setAuditOp(operatorDeleteBO.getAuditor());
            //同步审核时 直接通过
            if ("1".equals(operatorDeleteBO.getAuditType())) {
                operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_PASS);
                Operator operator = new Operator();
                DtoUtils.cloneBeanToBean(operator, operatorCopy);
                operatorCopyMapper.insert(operatorCopy);
                int result = operatorMapper.deleteOperator(operator);
                if (result <= 0) {
                    return GetResult.getResultErr("删除失败！");
                }
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                continue;
            }
            operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
            int result1 = getResult1(operator1);
            int result2 = operatorCopyMapper.insert(operatorCopy);
            //返回处理结果
            if (result1 <= 0 && result2 <= 0) {
                log.info("删除用户信息：删除失败");
                return GetResult.getResultFail("删除失败");
            }
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("删除用户信息：删除成功，待审核。审核编号: {}", operatorCopy.getAuditId());
        }
        String message = "1".equals(deleteBO.getAuditType()) ? "删除成功！" : "删除成功，待审核！";
        return GetResult.getResultSuccess(message);
    }

    /**
     * @Description: 重置密码
     * @Author: jiy.fang
     * @Date: 2019/7/23 23:47
     */
    @Override
    public BaseResult resetPwd(HttpServletRequest request, ResetPasswordBO resetPasswordBO) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(resetPasswordBO.getOpId());
        //定义日志信息
        String logName = TblLogConst.OPERATOR_RESET_PWD;
        String operationDesc = "操作人" + opName + "将用户" + resetPasswordBO.getOpName() + "进行重置密码";

        // 密码重置
        Operator operatorResetPwd = new Operator();
        operatorResetPwd.setOpId(resetPasswordBO.getOpId());
        // 重置状态
        operatorResetPwd.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
        // 重置初始密码
        operatorResetPwd.setOpPwd(DigestUtils.md5DigestAsHex(initPwd.getBytes()));
        // 重置密码次数
        operatorResetPwd.setOpPwdErrnum(0);
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        formatter.format(date);
        operatorResetPwd.setUpdateTime(date.toString());


        Integer result = operatorMapper.updateOperator(operatorResetPwd);
        if (result > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("用户密码重置：重置成功: {}", opName);
            return GetResult.getResultSuccess("重置密码成功！");
        }
        log.info("用户密码重置：重置失败: {}", opName);
        return GetResult.getResultFail("重置密码失败");

        // 去掉锁具管关联状态的校验  暂时注释
        // 判断是否符合重置密码的条件
        /* if (Integer.parseInt(StatusConstants.OPERATPR_LOCK) != operator.getOpStatus() && Integer.parseInt(StatusConstants.OPERATPR_NORMAL) != operator.getOpStatus()) {
            return GetResult.getResultFail("重置密码失败,非启用或锁定状态用户无法重置");
        } */

        // 密码重置不审核  暂时注释
        /* OperatorCopy operatorCopy = operatorCopyMapper.getOperatorCopyById(resetPasswordBO.getOpId());
        if (operatorCopy != null) {
            return GetResult.getResultFail("重置密码失败,该用户存在待审核记录");
        }
        Operator operator1 = operatorMapper.getOperatorByOpId(resetPasswordBO.getOpId());
        int terminalCount = terminalMapper.getCountByAdminId(resetPasswordBO.getOpId());
        if (terminalCount > 0) {
            return GetResult.getResultFail("用户" + operator1.getOpName() + "已绑定终端，操作失败");
        }
        List<String> openLockOpList = taskMapper.getOpenLockOp();
        int flag = 0;
        for (String openLockOp : openLockOpList) {
            String[] openLockOps = openLockOp.split(",");
            for (String name : openLockOps) {
                if (name.equals(operator1.getOpName())) {
                    flag++;
                }
            }
        }
        if (flag > 0) {
            return GetResult.getResultFail("用户" + operator1.getOpName() + "已绑定任务，操作失败");
        } */

        // 密码重置不审核  暂时注释
        //获取审核前的记录 用于审核前后对比
        /* OperatorDTO operatorDTO = operatorMapper.getOperatorDTOByOpId(resetPasswordBO.getOpId());
        operatorCopy = new OperatorCopy();
        DtoUtils.cloneBeanToBean(operatorCopy, operator);
        if (operator.getOpStatus() == Integer.parseInt(StatusConstants.OPERATPR_LOCK)) {
            operatorCopy.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
        }
        operatorCopy.setEntityRecord(JSON.toJSONString(operatorDTO));
        operatorCopy.setAuditId(PrimaryKeyUtil.getPrimaryKey());
        operatorCopy.setAuditType(StatusConstant.AUDIT_TYPE_RESETPWD);
        operatorCopy.setCreateOp(opId);
        operatorCopy.setOpPwd(DigestUtils.md5DigestAsHex(initPwd.getBytes()));
        operatorCopy.setOpPwdErrnum(0);
        operatorCopy.setAuditSn(operatorCopyMapper.maxAuditSn(operator.getOpId()) + 1);
        operatorCopy.setAuditor(resetPasswordBO.getAuditor());
        operatorCopy.setAuditOp(resetPasswordBO.getAuditor()); */

        // 密码重置不审核  暂时注释
        //同步审核时 直接通过
        /* if ("1".equals(resetPasswordBO.getAuditType())) {
            operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_PASS);
            Operator operatorResetPwd = new Operator();

            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            formatter.format(date);
            operatorResetPwd.setUpdateTime(date.toString());

            DtoUtils.cloneBeanToBean(operatorResetPwd, operatorCopy);
            operatorResetPwd.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
            operatorCopyMapper.insert(operatorCopy);
            Integer result = operatorMapper.updateOperator(operatorResetPwd);
            if (result > 0) {
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("重置密码成功！");
            }
            return GetResult.getResultErr("重置密码失败");
        }
        operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
        int result1 = getResult1(operator);
        //将操作信息添加到审核表
        int result2 = operatorCopyMapper.insert(operatorCopy);
        //返回结果
        if (result1 > 0 && result2 > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("用户密码重置：重置成功，待审核。审核编号: {}", operatorCopy.getAuditId());
            return GetResult.getResultSuccess("密码重置成功，待审核！");
        }
        log.info("用户密码重置：重置失败");
        return GetResult.getResultFail("重置失败"); */
    }

    /**
     * 重置初始化密码
     * @param request
     * @param resetInitPasswordBO
     * @return
     * @throws Exception
     */
    @Override
    public BaseResult resetInitPwd(HttpServletRequest request, ResetInitPasswordBO resetInitPasswordBO) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(resetInitPasswordBO.getOpId());
        //定义日志信息
        String logName = TblLogConst.OPERATOR_RESET_INIT_PWD;
        String operationDesc = "操作人" + opName + "将用户" + resetInitPasswordBO.getOpName() + "重置初始化密码";

        // 密码重置
        Operator operatorResetPwd = new Operator();
        operatorResetPwd.setOpId(resetInitPasswordBO.getOpId());
        // 重置状态
        operatorResetPwd.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
        // 重置初始密码
        operatorResetPwd.setOpPwd(resetInitPasswordBO.getOpPwd());
        // 重置密码次数
        operatorResetPwd.setOpPwdErrnum(0);
        operatorResetPwd.setFirstLogin("1");
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        formatter.format(date);
        operatorResetPwd.setUpdateTime(date.toString());


        Integer result = operatorMapper.updateOperator(operatorResetPwd);
        if (result > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("用户密码重置：重置成功: {}", opName);
            return GetResult.getResultSuccess("重置密码成功！");
        }
        log.info("用户密码重置：重置失败: {}", opName);
        return GetResult.getResultFail("重置密码失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult batchResetPwd(HttpServletRequest request, ResetPasswordBO resetBO) throws Exception {
        String[] opIds = resetBO.getOpId().split(",");
        for (String operateId : opIds) {
            ResetPasswordBO resetPasswordBO = new ResetPasswordBO();
            BeanUtil.copyProperties(resetBO, resetPasswordBO);
            resetPasswordBO.setOpId(operateId);
            BaseResult result = resetPwd(request, resetPasswordBO);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        // String message = "1".equals(resetBO.getAuditType()) ? "密码重置成功！" : "密码重置成功，待审核！";
        return GetResult.getResultSuccess("密码重置成功！");
    }

    /**
     * @Description: 登录解锁
     * @Author: jiy.fang
     * @Date: 2019/7/23 09:46
     */
    @Override
    public BaseResult unlockOperator(HttpServletRequest request, UnlockOperatorBO unlockOperatorBO) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(unlockOperatorBO.getOpId());
        // 定义日志信息
        String logName = TblLogConst.OPERATOR_UNLOCK;
        String operationDesc = "操作人" + opName + "将用户" + unlockOperatorBO.getOpName() + "进行登录解锁";

        // 判断是否符合用户解锁的条件
        if (Integer.parseInt(StatusConstants.OPERATPR_LOCK) != operator.getOpStatus()) {
            return GetResult.getResultFail("该用户不处于锁定状态，无须解锁");
        }

        // 密码解锁
        Operator unlockOperator = new Operator();
        unlockOperator.setOpId(unlockOperatorBO.getOpId());
        // 初始化状态
        unlockOperator.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
        // 重置密码次数
        unlockOperator.setOpPwdErrnum(0);

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        formatter.format(date);
        unlockOperator.setUpdateTime(date.toString());

        Integer result = operatorMapper.updateOperator(unlockOperator);
        if (result > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("登录解锁：解锁成功: {}", opName);
            return GetResult.getResultSuccess("登录解锁成功！");
        }
        log.info("登录解锁：解锁失败: {}", opName);
        return GetResult.getResultFail("登录解锁失败");

        // 密码解锁无需审核 以下全部暂时注释
        /* OperatorCopy operatorCopy = operatorCopyMapper.getOperatorCopyByIdUnlock(unlockOperatorBO.getOpId());
        if (operatorCopy != null && StatusConstant.AUDIT_TYPE_UNLOCK.equals(operatorCopy.getAuditType())) {
            return GetResult.getResultFail("用户" + unlockOperatorBO.getOpId() + "有待审核记录，无法解锁");
        } */


        // 密码解锁不校验绑定终端 绑定任务  暂时注释
        /* Operator operator1 = operatorMapper.getOperatorByOpId(unlockOperatorBO.getOpId());
        int terminalCount = terminalMapper.getCountByAdminId(unlockOperatorBO.getOpId());
        if (terminalCount > 0) {
            return GetResult.getResultFail("用户" + operator1.getOpName() + "已绑定终端，操作失败");
        }
        List<String> openLockOpList = taskMapper.getOpenLockOp();
        for (String openLockOp : openLockOpList) {
            String[] openLockOps = openLockOp.split(",");
            for (String name : openLockOps) {
                if (name.equals(operator1.getOpName())) {
                    return GetResult.getResultFail("用户" + operator1.getOpName() + "已绑定任务，操作失败");
                }
            }
        } */

        // 密码解锁无需审核 暂时注释
        // 获取审核前的记录 用于审核前后对比
        /* OperatorDTO operatorDTO = operatorMapper.getOperatorDTOByOpId(unlockOperatorBO.getOpId());

        operatorCopy = new OperatorCopy();
        DtoUtils.cloneBeanToBean(operatorCopy, operator);
        operatorCopy.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
        operatorCopy.setOpPwdErrnum(0);
        operatorCopy.setAuditId(PrimaryKeyUtil.getPrimaryKey());
        operatorCopy.setAuditType(StatusConstant.AUDIT_TYPE_UNLOCK);
        operatorCopy.setCreateOp(opId);
        operatorCopy.setAuditSn(operatorCopyMapper.maxAuditSn(operator.getOpId()) + 1);
        operatorCopy.setAuditor(unlockOperatorBO.getAuditor());
        operatorCopy.setAuditOp(unlockOperatorBO.getAuditor());
        operatorCopy.setEntityRecord(JSON.toJSONString(operatorDTO)); */

        // 密码解锁无需审核 暂时注释
        //同步审核时 直接通过
        /* if ("1".equals(unlockOperatorBO.getAuditType())) {
            operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_PASS);
            Operator unlockOperator = new Operator();

            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            formatter.format(date);
            unlockOperator.setUpdateTime(date.toString());

            DtoUtils.cloneBeanToBean(unlockOperator, operatorCopy);
            unlockOperator.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
            operatorCopyMapper.insert(operatorCopy);
            Integer result = operatorMapper.updateOperator(unlockOperator);
            if (result > 0) {
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("登录解锁成功！");
            }
            return GetResult.getResultErr("登录解锁失败");
        } */


        // operator.setAuditStatus(StatusConstant.INSPECT_STATUS_AWAIT);
        // operatorMapper.updateOperatorAuditStatus(operator);


        /* operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
        int result1 = getResult1(operator);
        //将操作信息添加到审核表
        int result2 = operatorCopyMapper.insert(operatorCopy);
        //返回结果
        if (result1 > 0 && result2 > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("登录解锁：解锁成功，待审核。审核编号: {}", operatorCopy.getAuditId());
            return GetResult.getResultSuccess("登录解锁成功，待审核！");
        }
        log.info("登录解锁：解锁失败");
        return GetResult.getResultFail("解锁失败"); */
    }

    @Override
    public BaseResult batchUnlock(HttpServletRequest request, UnlockOperatorBO unlockBO) throws Exception {
        String[] opids = unlockBO.getOpId().split(",");
        for (String operateId : opids) {
            UnlockOperatorBO unlockOperatorBO = new UnlockOperatorBO();
            BeanUtil.copyProperties(unlockBO, unlockOperatorBO);
            unlockOperatorBO.setOpId(operateId);
            BaseResult result = unlockOperator(request, unlockOperatorBO);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        // String message = "1".equals(unlockBO.getAuditType()) ? "登录解锁成功！" : "登录解锁成功，待审核！";
        return GetResult.getResultSuccess("登录解锁成功！");
    }

    /**
     * @Description: 用户启用
     * @Author: jiy.fang
     * @Date: 2019/7/24 1:02
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult enableOperator(HttpServletRequest request, EnableOperatorBO enableOperatorBO) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        //定义日志信息
        String logName = TblLogConst.OPERATOR_ENABLE;
        String operationDesc = "操作人" + opName + "将用户 " + enableOperatorBO.getOpName() + " 进行启用";

        Operator operator = operatorMapper.getOperatorByOpId(enableOperatorBO.getOpId());
        if (opId.equals(operator.getOpId())) {
            return GetResult.getResultFail("启用失败，不可启用操作用户自己");
        }
        //判断是否符合的条件
        if (Integer.parseInt(StatusConstants.OPERATPR_DISABLE) != operator.getOpStatus()) {
            return GetResult.getResultFail("启用失败，非停用用户无法启用");
        }
        OperatorCopy operatorCopy = operatorCopyMapper.getOperatorCopyById(enableOperatorBO.getOpId());
        if (operatorCopy != null) {
            return GetResult.getResultFail("启用失败，用户" + enableOperatorBO.getOpId() + "有待审核操作");
        }
        //获取审核前的记录 用于审核前后对比
        OperatorDTO operatorDTO = operatorMapper.getOperatorDTOByOpId(enableOperatorBO.getOpId());

        operatorCopy = new OperatorCopy();
        DtoUtils.cloneBeanToBean(operatorCopy, operator);
        operatorCopy.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
        operatorCopy.setAuditId(PrimaryKeyUtil.getPrimaryKey());
        operatorCopy.setAuditType(StatusConstant.AUDIT_TYPE_ENABLE);
        operatorCopy.setCreateOp(opId);
        operatorCopy.setAuditSn(operatorCopyMapper.maxAuditSn(operator.getOpId()) + 1);
        operatorCopy.setAuditor(enableOperatorBO.getAuditor());
        operatorCopy.setAuditOp(enableOperatorBO.getAuditor());
        operatorCopy.setEntityRecord(JSON.toJSONString(operatorDTO));
        //同步审核时 直接通过
        if ("1".equals(enableOperatorBO.getAuditType())) {
            operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_PASS);
            Operator enableOperator = new Operator();

            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            formatter.format(date);
            enableOperator.setUpdateTime(date.toString());

            DtoUtils.cloneBeanToBean(enableOperator, operatorCopy);
            enableOperator.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_NORMAL));
            operatorCopyMapper.insert(operatorCopy);
            Integer result = operatorMapper.updateOperator(enableOperator);
            if (result > 0) {
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("用户启用成功！");
            }
            return GetResult.getResultErr("用户启用失败");
        }
        operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
        int result1 = getResult1(operator);
        //将操作信息添加到审核表
        int result2 = operatorCopyMapper.insert(operatorCopy);
        //返回结果
        if (result1 > 0 && result2 > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("用户启用：启用成功，待审核。审核编号: {}", operatorCopy.getAuditId());
            return GetResult.getResultSuccess("用户启用成功，待审核！");
        }
        log.info("用户启用：启用失败");
        return GetResult.getResultFail("启用失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult batchEnable(HttpServletRequest request, EnableOperatorBO enableBO) throws Exception {
        String[] opids = enableBO.getOpId().split(",");
        for (String operateId : opids) {
            EnableOperatorBO enableOperatorBO = new EnableOperatorBO();
            BeanUtil.copyProperties(enableBO, enableOperatorBO);
            enableOperatorBO.setOpId(operateId);
            BaseResult result = enableOperator(request, enableOperatorBO);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        String message = "1".equals(enableBO.getAuditType()) ? "用户启用成功！" : "用户启用成功，待审核！";
        return GetResult.getResultSuccess(message);
    }

    /**
     * @Description: 用户停用
     * @Author: jiy.fang
     * @Date: 2019/7/24 1:20
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult disableOperator(HttpServletRequest request, DisableOperatorBO disableOperatorBO) throws Exception {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        //定义日志信息
        String logName = TblLogConst.OPERATOR_DISABLE;
        String operationDesc = "操作人" + opName + "将用户 " + disableOperatorBO.getOpName() + " 进行停用";

        Operator operator = operatorMapper.getOperatorByOpId(disableOperatorBO.getOpId());
        if (opId.equals(operator.getOpId())) {
            return GetResult.getResultFail("停用失败，不可停用操作用户自己");
        }
        //判断是否符合的条件
        if (Integer.parseInt(StatusConstants.OPERATPR_NORMAL) != operator.getOpStatus()) {
            return GetResult.getResultFail("非启用用户不能停用");
        }
        OperatorCopy operatorCopy = operatorCopyMapper.getOperatorCopyById(disableOperatorBO.getOpId());
        if (operatorCopy != null) {
            return GetResult.getResultFail("用户有待审核操作，无法停用用户");
        }
        // int terminalCount = terminalMapper.getCountByAdminId(disableOperatorBO.getOpId());
        // if (terminalCount > 0) {
        //     return GetResult.getResultFail("用户" + operator.getOpName() + "已绑定终端，操作失败");
        // }
        // List<String> openLockOpList = taskMapper.getOpenLockOp();
        // for (String openLockOp : openLockOpList) {
        //     String[] openLockOps = openLockOp.split(",");
        //     for (String name : openLockOps) {
        //         if (name.equals(operator.getOpName())) {
        //             return GetResult.getResultFail("用户" + operator.getOpName() + "已绑定任务，操作失败");
        //         }
        //     }
        // }
        //获取审核前的记录 用于审核前后对比
        OperatorDTO operatorDTO = operatorMapper.getOperatorDTOByOpId(disableOperatorBO.getOpId());
        operatorCopy = new OperatorCopy();
        DtoUtils.cloneBeanToBean(operatorCopy, operator);
        operatorCopy.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_DISABLE));
        operatorCopy.setAuditId(PrimaryKeyUtil.getPrimaryKey());
        operatorCopy.setAuditType(StatusConstant.AUDIT_TYPE_DISABLE);
        operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
        operatorCopy.setCreateOp(opId);
        operatorCopy.setAuditSn(operatorCopyMapper.maxAuditSn(operator.getOpId()) + 1);
        operatorCopy.setAuditor(disableOperatorBO.getAuditor());
        operatorCopy.setAuditOp(disableOperatorBO.getAuditor());
        operatorCopy.setEntityRecord(JSON.toJSONString(operatorDTO));
        //同步审核时 直接通过
        if ("1".equals(disableOperatorBO.getAuditType())) {
            operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_PASS);
            Operator disableOperator = new Operator();

            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            formatter.format(date);
            disableOperator.setUpdateTime(date.toString());

            DtoUtils.cloneBeanToBean(disableOperator, operatorCopy);
            disableOperator.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_DISABLE));
            operatorCopyMapper.insert(operatorCopy);
            Integer result = operatorMapper.updateOperator(disableOperator);
            //删除调拨任务前清除锁具在新机构的有效任务
            resetBrcTask(operator.getOpName());
            //删除关联任务
            znsTaskMapper.deleteBYOp(operator.getOpName());
            terminalMapper.updateByAdminId(operator.getOpId());
            if (result > 0 ) {
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("用户停用成功！");
            }
            return GetResult.getResultErr("用户停用失败");
        }
        operatorCopy.setAuditFlag(StatusConstant.AUDIT_FLAG_DEFAULT);
        int result1 = getResult1(operator);
        //将操作信息添加到审核表
        int result2 = operatorCopyMapper.insert(operatorCopy);
        //返回结果
        if (result1 > 0 && result2 > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            log.info("用户停用：停用成功，待审核。审核编号: {}", operatorCopy.getAuditId());
            return GetResult.getResultSuccess("用户停用成功，待审核！");
        }
        log.info("用户停用：停用失败");
        return GetResult.getResultFail("停用失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult batchDisable(HttpServletRequest request, DisableOperatorBO disableBO) throws Exception {
        String[] opids = disableBO.getOpId().split(",");
        for (String operateId : opids) {
            DisableOperatorBO disableOperatorBO = new DisableOperatorBO();
            BeanUtil.copyProperties(disableBO, disableOperatorBO);
            disableOperatorBO.setOpId(operateId);
            BaseResult result = disableOperator(request, disableOperatorBO);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        String message = "1".equals(disableBO.getAuditType()) ? "用户停用成功！" : "用户停用成功，待审核！";
        return GetResult.getResultSuccess(message);
    }

    /**
     * @Description: 用户导出
     * @Author: jiy.fang
     * @Date: 2019/7/24 10:16
     */
    @Override
    public List<Operator> getListOperatorExport(HttpServletRequest request, OperatorQueryBO queryBO) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        List<String> orgIdsList = getListOrgIds(orgId);
        orgIdsList.add(orgId);
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("list", orgIdsList);
        queryMap.put("opName", queryBO.getOpName());
        queryMap.put("opRealname", queryBO.getOpRealname());
        queryMap.put("roleId", queryBO.getRoleId());
        queryMap.put("adminName", adminName);
        return operatorMapper.getListOperatorByPage(queryMap);
    }

    @Override
    public String userConvert(String userIds) {
        String[] users = userIds.split(",");
        ArrayList<String> list = new ArrayList<>();
        if (users.length > 1) {
            for (String s : users) {
                StringBuffer buffer = new StringBuffer();
                Operator operatorByOpName = operatorMapper.getOperatorByOpName(s);
                buffer.append(operatorByOpName.getOpRealname());
                buffer.append("-");
                buffer.append(s);
                list.add(buffer.toString());
            }
        } else {
            StringBuffer buffer = new StringBuffer();
            Operator operatorByOpName = operatorMapper.getOperatorByOpName(users[0]);
            buffer.append(operatorByOpName.getOpRealname());
            buffer.append("-");
            buffer.append(users[0]);
            list.add(buffer.toString());
        }
        return StringUtils.join(list, ",");
    }

    /**
     * @Description: 判断浏览器是否已经登录
     * @Author: jiy.fang
     * @Date: 2019/9/6 14:22
     */
    @Override
    public String checklogin(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (opId != null) {
            String redisSessionId = redisTemplate.opsForValue().get(TokenUtil.getOpName(request.getHeader("token")));
            if (redisSessionId != null && redisSessionId.equals(session.getId())) {
                LoginBackDTO loginBackDTO = operatorMapper.getBackInfoByOpId(opId);
                return CommonConst.getResult("002", loginBackDTO);
            }
        }
        return CommonConst.getResult("001", "需要进行登录验证");
    }

    @Override
    public BaseResult<LoginBackDTO> getOperatorInfo(HttpServletRequest request) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        LoginBackDTO loginBackDTO = operatorMapper.getBackInfoByOpId(opId);
        return GetResult.getResult(loginBackDTO);
    }

    @Override
    public BaseResult<List<PcInspect>> selectInspect(String orgId) {
        List<PcInspect> pcInspects = operatorMapper.selectInspect(orgId);
        return GetResult.getResult(pcInspects);
    }

    /**
     * @Description: 判断是否需要修改密码
     * @Author: jiy.fang
     * @Date: 2019/7/17 8:44
     */
    private BaseResult<LoginBackDTO> checkIsNeedChangePwd(HttpServletResponse response, HttpServletRequest request,
                                                          Operator operator, String pwd) {

        log.info("登录类型:1-密码 2-指纹,此次登录为：{}", operator.getLoginType());
        //定义日志信息
        String logName = "指纹登录";
        String operationDesc = "操作人" + operator.getOpName() + "指纹登录系统";
        if ("1".equals(operator.getLoginType())){
            logName = TblLogConst.OPERATOR_PWD_LOGIN;
            operationDesc = "操作人" + operator.getOpName() + "密码登录系统";
        } else if ("2".equals(operator.getLoginType())){
            logName = TblLogConst.OPERATOR_FINGER_LOGIN;
            operationDesc = "操作人" + operator.getOpName() + "指纹登录系统";
        }
        //检查用户是否有登录权限
        String key = "popedom:loginOperator:" + operator.getRoleId();
        RedisUtil.set("ceshi:ceshiyong", "DYBDSB");
        //获取权限
        List<Popedom> popedomList = popedomMapper.getPopedomByRoleId(operator.getRoleId());
        RedisUtil.set(key, popedomList);
        if (popedomList.isEmpty()) {
            redisUtils.delete(key);
            return GetResult.getResultFail("没有任何管理权限,无法登陆");
        }
        LoginBackDTO loginBackDTO = operatorMapper.getBackInfoByOpId(operator.getOpId());

        Map<String, String> map = new HashMap<>();
        map.put("username", operator.getOpName());
        map.put("orgId", operator.getOrgId());
        map.put("password", pwd);
        map.put("applicationId", "ManageRealm");
        try {
            log.info("登录人生成token前参数:{}",map);
            Map<String, String> authInfo = (Map<String, String>) authrozationClient.fetchToken(map);
            log.info("登录人生成token后参数:{}",authInfo);
            if (!"00".equals(authInfo.get("respCode"))) {
                return GetResult.getResultFail("获取权限失败");
            }
            response.setHeader("Authorization", authInfo.get("transInfo"));
            response.setHeader("Access-Control-Expose-Headers", "Authorization");
        } catch (Exception e) {
            log.error("获取权限失败:{}",e);
            return GetResult.getResultFail("获取权限失败");
        }
        Boolean bool = null;
        //比较用户密码和初始密码
        if ("1".equals(operator.getFirstLogin())
                && "1".equals(loginBackDTO.getLoginType())) {
            //用户需要修改密码
            return GetResult.getResultCodeAndMessage(CommonConst.RET_RESET, OperatorConst.OPERATOR_UPDATE_PWD);
        }
        /**
         * 20220917 tk 如果是指纹登录，再记录此日志，密码登录日志在其他位置进行记录
         */
        if ("2".equals(operator.getLoginType())) {
            operatorLogService.insert(operationDesc, logName, "1", operator.getOpId(), operator.getOpName(), operator.getOrgId());
        }
        log.info("登录成功,用户ID={}，用户名={}", operator.getOpId(), operator.getOpName());
        return GetResult.getResult(loginBackDTO);
    }

    /**
     * @Description: 查询登录用户的权限
     * @Author: jiy.fang
     * @Date: 2019/7/30 23:07
     */
    private List<Popedom> getOperatorPopedom(Operator operator) {
        List<Popedom> popedomList = new ArrayList<>();
        List<Popedom> orgPopedoms = popedomMapper.getPopedomByOrgId(operator.getOrgId());
        List<Popedom> rolePopedoms = popedomMapper.getPopedomByRoleId(operator.getRoleId());
        for (int i = 0; i < orgPopedoms.size(); i++) {
            for (int j = 0; j < rolePopedoms.size(); j++) {
                if (orgPopedoms.get(i).getPopedomId().equals(rolePopedoms.get(j).getPopedomId())) {
                    popedomList.add(orgPopedoms.get(i));
                }
            }
        }
        return popedomList;
    }

    /**
     * @Description: 根据机构码获取子机构码列表
     * @Author: jiy.fang
     * @Date: 2019/7/19 15:18
     */
    @Override
    public List<String> getListOrgIds(String orgId) {
        String strkey = "orgid:" + orgId;
        List<String> lists = null;
        lists = redisUtils.get(strkey, List.class);
        if (lists == null) {
            lists = new ArrayList<>();
            recursiveGetOrgId(lists, orgId);
            redisUtils.set(strkey, lists);
        }

        return lists;
    }

    /**
     * 根据当前登录账号 所属机构的角色查询 当前机构同等角色的用户 以及上一级 机构的同等角色的用户
     *
     * @param operatorQueryBO
     * @return
     */
    @Override
    public BaseResult<List<Operator>> getOperatorListByRoleOrg(HttpServletRequest request, OperatorQueryBO operatorQueryBO) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        //获取当前操作菜单所对应的审核ID
        String popedomId = popedomMapper.getPopedomRelationByPopedomId(operatorQueryBO.getPopedomId());
        if (popedomId == null) {
            return GetResult.getResultErr("获取当前操作菜单所对应的审核ID失败");
        }
        //根据审核ID获取相应的角色
        List<String> roleIds = popedomMapper.getRoleIdByPopedomId(popedomId);
        //获取当前机构的上一级机构
        Organization organization = organizationMapper.getOrganizationByOrgId(orgId);

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("opId", opId);
        queryMap.put("roleIds", roleIds);
        queryMap.put("orgId", organization.getOrgId());
        queryMap.put("orgPid", organization.getOrgPid());
        List<Operator> operatorList = operatorMapper.getOperatorListByRoleOrg(queryMap);
        return GetResult.getResult(operatorList);
    }

    @Override
    public BaseResult<List<PcInspect>> auditPassword(AuditPasswordBo auditPasswordBo) throws Exception {
        Operator loginOperator = operatorMapper.getOperatorByOpId(auditPasswordBo.getAuditor());
        if (loginOperator == null) {
            log.info("用户名不存在");
            return GetResult.getResultErr("账号密码错误");
        }
        // 用户状态0：启用 1：停用 2：注销 3：密码锁定
        if (StatusConstants.OPERATPR_LOCK.equals(loginOperator.getOpStatus().toString())) {
            return GetResult.getResultErr(OperatorConst.LOGIN_OP_LOCK_ERROR);
        }
        if (StatusConstants.OPERATPR_LOGOFF.equals(loginOperator.getOpStatus().toString())) {
            return GetResult.getResultErr("账户已经注销，无法登录");
        }
        if (StatusConstants.OPERATPR_DISABLE.equals(loginOperator.getOpStatus().toString())) {
            return GetResult.getResultErr("账户处于停用状态，无法登录");
        }
        //验证用户密码
        if (!loginOperator.getOpPwd().equals(auditPasswordBo.getOpPwd())) {
            if (adminName.equals(loginOperator.getOpName())) {
                return GetResult.getResultErr("密码错误");
            } else {
                // 进行密码输入错误次数的统计
                // 设定在30分钟内连续输入5次锁定账户
                Integer loginErrorTimeRangInt = Integer.parseInt(loginErrorTimeRang);
                if (loginErrorTimeRangInt > 0) {
                    long timeout = loginErrorTimeRangInt * 60;
                    Date beginTime = null;
                    if (loginOperator.getOpErrortime() != null && !"".equals(loginOperator.getOpErrortime())) {
                        beginTime = DateFormat.getDate("yyyy-MM-dd HH:mm:ss", loginOperator.getOpErrortime());
                    }
                    Date endTime = new Date();
                    if (beginTime != null && DateFormat.comPareDate(beginTime, endTime) < timeout) {
                        //密码错误次数加1
                        loginOperator.setOpPwdErrnum(loginOperator.getOpPwdErrnum() + 1);
                        loginOperator.setOpErrortime(DateFormat.dateTimeFormat1(endTime));
                    } else {
                        loginOperator.setOpPwdErrnum(1);
                        loginOperator.setOpErrortime(DateFormat.dateTimeFormat1(endTime));
                    }
                    //比较密码错误次数
                    OtherParam otherParam = otherParamMapper.queryByConfKey(OtherParam.LOGIN_FAIL_TIMES);
                    int loginErrorCount = Integer.parseInt(otherParam.getConfValue());
                    loginOperator.setUpdateTime(DateFormat.dateTimeFormat1(endTime));
                    //设置为空不更新该字段
                    loginOperator.setOpLastLoginTime(null);
                    if (loginErrorCount > 0 && loginOperator.getOpPwdErrnum() >= loginErrorCount) {
                        loginOperator.setOpStatus(Integer.parseInt(StatusConstants.OP_STATUS_LOCKED));
                        //更新用户表信息
                        operatorMapper.updateOperator(loginOperator);
                        return GetResult.getResultErr("账户被锁定，请联系管理员解锁");
                    } else {
                        //更新用户表信息
                        operatorMapper.updateOperator(loginOperator);
                        return GetResult.getResultErr("账号密码错误");
                    }
                }
            }
        }
        loginOperator.setOpPwdErrnum(0);
        loginOperator.setOpErrortime(null);
        loginOperator.setOpLastLoginTime(DateFormat.dateTimeFormat1(new Date()));
        //更新用户表信息
        operatorMapper.updateOperator(loginOperator);
        return GetResult.getResultSuccess("成功！");
    }

    /**
     * 转授权
     *
     * @param authorityUpdateBo 转授权
     * @return list
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateAuthority(HttpServletRequest request, AuthorityUpdateBo authorityUpdateBo) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        //定义日志信息
        String logName = "转授权";

        if (authorityUpdateBo.getOpId().equals(authorityUpdateBo.getToAuthorizedId())) {
            return GetResult.getResultFail("被授权人不能是自己！");
        }
        //获取授权人权限
        Operator operator = operatorMapper.getOperatorByOpId(authorityUpdateBo.getOpId());
        //获取被授权人权限
        Operator toOperator = operatorMapper.getOperatorByOpId(authorityUpdateBo.getToAuthorizedId());
        String operationDesc = operator.getOpName() + " 转授权给 " + toOperator.getOpName();
        List<String> openLockOpList = taskMapper.getOpenLockOp();
        for (String openLockOp : openLockOpList) {
            String[] openLockOps = openLockOp.split(",");
            for (String name : openLockOps) {
                if (name.equals(operator.getOpName())) {
                    return GetResult.getResultFail("用户" + operator.getOpName() + "已绑定任务，请先删除关联任务");
                }
                if (name.equals(toOperator.getOpName())) {
                    return GetResult.getResultFail("用户" + toOperator.getOpName() + "已绑定任务，请先删除关联任务");
                }
            }
        }
        //权限互换
        int result = operatorMapper.updateOperatorByOpId(operator.getOpId(), toOperator.getRoleId(), toOperator.getOpId());
        int toResult = operatorMapper.updateOperatorByOpId2(toOperator.getOpId(), operator.getRoleId(), "2"); // 2 表示被授权
        if (result > 0 && toResult > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("转授权成功！");
        }
        return GetResult.getResultErr("转授权失败！");
    }

    /**
     * 取消转授权
     *
     * @param authorityUpdateBo 取消转授权
     * @return list
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult rollBackAuthority(HttpServletRequest request, AuthorityUpdateBo authorityUpdateBo) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        //定义日志信息
        String logName = "取消转授权";
        //查找授权人信息
        Operator authOperator = operatorMapper.getOperatorByOpId(authorityUpdateBo.getOpId());
        //Operator opOperator= operatorMapper.getOperatorByOpId(authOperator.getOpId());
        String operationDesc = authOperator.getOpName() + "取消转授权 ";
        if (authorityUpdateBo.getOpId() != null && authorityUpdateBo.getToAuthorizedId() == null) {
            //授权人进行取消授权
            //获取授权人信息
            Operator operator = operatorMapper.getOperatorByOpId(authorityUpdateBo.getOpId());
            //获取被授权人信息
            Operator toOperator = operatorMapper.getOperatorByOpId(operator.getSublicense());
            List<String> openLockOpList = taskMapper.getOpenLockOp();
            for (String openLockOp : openLockOpList) {
                String[] openLockOps = openLockOp.split(",");
                for (String name : openLockOps) {
                    if (name.equals(operator.getOpName())) {
                        return GetResult.getResultFail("用户" + operator.getOpName() + "已绑定任务，请先删除关联任务");
                    }
                    if (name.equals(toOperator.getOpName())) {
                        return GetResult.getResultFail("用户" + toOperator.getOpName() + "已绑定任务，请先删除关联任务");
                    }
                }
            }
            //权限互换
            int result = operatorMapper.rollBackAuthority(operator.getOpId(), toOperator.getRoleId(), null);
            int toResult = operatorMapper.updateOperatorByOpId2(toOperator.getOpId(), operator.getRoleId(), "0"); //0表示未授权
            if (result > 0 && toResult > 0) {
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("授权回退成功！");
            }
            return GetResult.getResultErr("授权回退失败！");
        } else {
            //被授权人进行取消授权
            //查找授权人信息
            Operator operator = operatorMapper.getOperatorBySublicense(authorityUpdateBo.getToAuthorizedId());
            //获取被授权人信息
            Operator toOperator = operatorMapper.getOperatorByOpId(operator.getSublicense());
            List<String> openLockOpList = taskMapper.getOpenLockOp();
            for (String openLockOp : openLockOpList) {
                String[] openLockOps = openLockOp.split(",");
                for (String name : openLockOps) {
                    if (name.equals(operator.getOpName())) {
                        return GetResult.getResultFail("用户" + operator.getOpName() + "已绑定任务，请先删除关联任务");
                    }
                    if (name.equals(toOperator.getOpName())) {
                        return GetResult.getResultFail("用户" + toOperator.getOpName() + "已绑定任务，请先删除关联任务");
                    }
                }
            }
            //权限互换
            int result = operatorMapper.rollBackAuthority(operator.getOpId(), toOperator.getRoleId(), null);
            int toResult = operatorMapper.updateOperatorByOpId2(toOperator.getOpId(), operator.getRoleId(), "0"); //0表示未授权
            if (result > 0 && toResult > 0) {
                operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
                return GetResult.getResultSuccess("授权回退成功！");
            }
            return GetResult.getResultErr("授权回退失败！");
        }
    }

    @Override
    public BaseResult<LoginBackDTO> handLogin(HttpServletResponse response, HttpServletRequest request, HandLoginBO handLoginBO) {
        //通过用户id获取用户信息
        Operator operator = operatorMapper.getOperatorById(handLoginBO.getOpId());
        if (ObjectUtil.isNull(operator)) {
            return GetResult.getResultFail("用户不存在");
        }
        //判断该用户是否是指纹登录用户
        if (!"2".equals(operator.getLoginType())) {
            return GetResult.getResultFail("该用户不支持指纹登录！");
        }
        // 用户状态0：启用 1：停用 2：注销 3：密码锁定
        if (StatusConstants.OPERATPR_LOCK.equals(operator.getOpStatus().toString())) {
            return GetResult.getResultFail(OperatorConst.LOGIN_OP_LOCK_ERROR);
        }
        if (StatusConstants.OPERATPR_LOGOFF.equals(operator.getOpStatus().toString())) {
            return GetResult.getResultFail("账户已经注销，无法登录");
        }
        if (StatusConstants.OPERATPR_DISABLE.equals(operator.getOpStatus().toString())) {
            return GetResult.getResultFail("账户处于停用状态，无法登录");
        }
        operator.setOpPwdErrnum(0);
        operator.setOpErrortime(null);
        operator.setOpLastLoginTime(DateFormat.dateTimeFormat1(new Date()));
        //更新用户表信息
        operatorMapper.updateOperator(operator);
        //继续判断登录条件
        return checkIsNeedChangePwd(response, request, operator, operator.getOpPwd());
    }

    @Override
    public BaseResult insertOperatorByImport(HttpServletRequest request, OperatorAddBO operatorAddBO, String roleName) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String org = getOrgIdAllChild(orgId);
        String[] orgIds = org.split(",");
        int flag = 0;
        for (String id : orgIds) {
            if (id.equals(operatorAddBO.getOrgId())) {
                flag++;
            }
        }
        if (flag == 0) {
            throw new Exception("所属机构不是当前机构或下属机构");
        }
        //通过角色名称查询角色ID
        String roleId = roleMapper.getRoleByRoleName(roleName);
        operatorAddBO.setRoleId(roleId);
        //定义日志信息
        String logName = TblLogConst.OPERATOR_ADD;
        String operationDesc = "操作人" + opName + " 添加了用户：" + operatorAddBO.getOpName();

        //判断用户名是否已经存在
        Operator operator2 = operatorMapper.getOperatorByOpNameString(operatorAddBO.getOpName());
        //int existOpName = operatorMapper.existOpName(operatorAddBO.getOpName());
        if(Objects.nonNull(operator2) && !operator2.getOpStatus().equals(2)){
            return GetResult.getResultFail("用户名：" + operatorAddBO.getOpName() + "已存在");
        }
        /*if (existOpName > 0) {
            return GetResult.getResultFail("用户名：" + operatorAddBO.getOpName() + "已存在");
        }*/
        //判断用户名是否在临时表中已经存在
        int existOpNameCopy = operatorCopyMapper.existOpName(operatorAddBO.getOpName());
        if (existOpNameCopy > 0) {
            return GetResult.getResultFail("用户：" + operatorAddBO.getOpName() + "已在审核");
        }
        int result;
        //添加用户到用户临时表
        Operator operator = new Operator();
        DtoUtils.cloneBeanToBean(operator, operatorAddBO);
        //生成审核ID
        operator.setOpId(PrimaryKeyUtil.getPrimaryKey());
        operator.setOpPwd(DigestUtils.md5DigestAsHex(initPwd.getBytes()));
        operator.setCreateOp(opId);
        operator.setOpPwdErrnum(0);
        operator.setFirstLogin("1");
        operator.setSublicenseStatus("0");
        operator.setOpStatus(Integer.parseInt(StatusConstants.OPERATPR_DISABLE));
        if(Objects.nonNull(operator2) && operator2.getOpStatus().equals(2)){
            operator.setOpId(null);
            result = operatorMapper.updateOperatorByOpName(operator);
        } else {
            //修改用户主表信息
            result = operatorMapper.insertOperator(operator);
        }
        if (result > 0) {
            //详细日志添加
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("添加成功！");
        }
        return GetResult.getResultErr("添加失败！");
    }

    public String getXml(String name) {
        String result = null;
        try {

            String endpoint = "http://22.200.1.93/bocpws/bocpcommon.asmx";
            org.apache.axis.client.Service service = new org.apache.axis.client.Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(endpoint));
            call.addParameter(new javax.xml.namespace.QName(
                            "http://tempuri.org/", "ticket"),
                    org.apache.axis.encoding.XMLType.XSD_STRING,
                    javax.xml.rpc.ParameterMode.IN);
            call.setReturnType(org.apache.axis.Constants.XSD_STRING);
            String sa = "http://tempuri.org/user_ticket";
            call.setOperationName(new javax.xml.namespace.QName(
                    "http://tempuri.org/", "user_ticket"));
            call.setUseSOAPAction(true);
            call.setSOAPActionURI(sa);
            result = (String) call.invoke(new Object[]{name});

        } catch (Exception e) {

            System.err.println(e.toString());
            e.printStackTrace();


        }
        return result;
    }

    public String readUserId(String xml) {
        Document doc = null;

        try {
            doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement();
            Element state = rootElt.element("state");
            if ("0".equals(state.getTextTrim())) {
                String sid = rootElt.element("sid").getTextTrim();
                String uid = rootElt.element("uid").getTextTrim();
                String expire_date = rootElt.element("expire_date").getTextTrim();
                return uid;
            } else {
                log.error("获取ticket用户状态失败,ticket内容:{}", xml);
            }
        } catch (Exception e) {
            log.error("获取ticket用户状态失败,ticket内容:{}", xml);
        }
        return null;
    }

    private String readStringFromCell(Cell cell) {
        if (cell == null) {
            return null;
        }
        return cell.getStringCellValue();
    }

    //递归查询子机构
    private void recursiveGetOrgId(List<String> lists, String orgId) {
        List<String> orgIdList = organizationMapper.getOrgIdsList(orgId);
        while (orgIdList.isEmpty()) {
            return;
        }
        for (String childOrgId : orgIdList) {
            lists.add(childOrgId);
            recursiveGetOrgId(lists, childOrgId);
        }
    }

    public String getOrgIdAllChild(String orgId) throws Exception {
        List<Organization> orgList = organizationService.getOrgIds(orgId);
        StringBuilder sb = new StringBuilder();
        for (Organization organization : orgList) {
            sb.append(organization.getOrgId()).append(",");
        }
        int size = sb.toString().length() - 1;
        return sb.toString().substring(0, size);
    }

    public void resetBrcTask(String opName){
        //查询调拨任务
        List<TaskZNSDTO> tasks = znsTaskMapper.findBrcByOpName(opName);
        if(CollectionUtil.isNotEmpty(tasks)){
           List<String> lockSnList=new ArrayList<>();
           for (TaskZNSDTO dto:tasks){
               String lockSn = dto.getLockSn();
               String[] lockSns = lockSn.split("/");
               List<String> list = Arrays.asList(lockSns);
               lockSnList.addAll(list);
           }
           //去重
           if(CollectionUtil.isNotEmpty(lockSnList)){
               lockSnList=lockSnList.stream().distinct().collect(Collectors.toList());
           }

            for (String lock : lockSnList) {
                Terminal terminal = terminalMapper.getTerminalBySn(lock, TerminalTypeEnum.LOCK.getCode());
                if (ObjectUtil.isNotNull(terminal) && StrUtil.isNotBlank(terminal.getOldOrg()) && StrUtil.isNotBlank(terminal.getOrgId())) {
                    //先清除锁具在新机构中的开锁任务
                    resetTask(terminal);
                    //回退锁具
                    terminalMapper.resetLockOrg(terminal.getId());
                }
            }
        }

    }

    public void resetTask(Terminal ter) {
        //清除锁具在新机构中的开锁任务
        TaskFindBO taskFindBO=new TaskFindBO();
        taskFindBO.setOrgId(ter.getOrgId());
        taskFindBO.setLockSn(ter.getTerminalSn());
        taskFindBO.setTimeScopeBegin(ter.getStartTime());
        taskFindBO.setTimeScopeEnd(ter.getEffectTime());
        List<TaskZNSDTO> taskZNSDTOS = znsTaskMapper.selectByCon(taskFindBO);
        if(CollectionUtil.isNotEmpty(taskZNSDTOS)){
            List<String> taskIds = taskZNSDTOS.stream().map(TaskZNSDTO::getTaskId).collect(toList());
            String[] split=new String[taskIds.size()];
            split=taskIds.toArray(split);
            znsTaskMapper.updateTaskState(split);
        }
    }
}
